import classNames from 'classnames';
import { useEffect, useRef } from 'react';
import styles from './index.module.scss';

// 1. 定义props的类型, 继承原生的接口类型
interface TextAreaProps
  extends React.DetailedHTMLProps<
    React.TextareaHTMLAttributes<HTMLTextAreaElement>,
    HTMLTextAreaElement
  > {
  value: string;
}
export default function Textarea(props: TextAreaProps) {
  // 1. 创建ref 💥HTMLTextAreaElement作为泛型
  const iptRef = useRef<HTMLTextAreaElement>(null);
  // 4. 设置初始值为true
  const {
    maxLength = 100,
    className,
    value,
    autoFocus = true,
    ...restProps
  } = props;

  // 3. 生命周期挂载后触发光标选中
  useEffect(() => {
    iptRef.current?.setSelectionRange(-1, -1);
  }, []);
  return (
    <div className={styles.root}>
      {/* 文本输入框 */}
      <textarea
        ref={iptRef}
        {...restProps}
        // 4 统计当前字数
        value={value}
        // {/* 3. className可以扩展  */}
        className={classNames('textarea', className)}
        autoFocus={autoFocus}
        maxLength={maxLength}
      />
      {/* 当前字数/最大允许字数 */}
      <div className="count">
        {value.length}/{maxLength}
      </div>
    </div>
  );
}
